package com.uliky.shouyiLibrary.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.uliky.common.utils.R;
import com.uliky.shouyiLibrary.cart.feign.ProductFeignService;
import com.uliky.shouyiLibrary.cart.interceptor.CartInterceptor;
import com.uliky.shouyiLibrary.cart.service.CartService;
import com.uliky.shouyiLibrary.cart.vo.CartItemVo;
import com.uliky.shouyiLibrary.cart.vo.CartVo;
import com.uliky.shouyiLibrary.cart.vo.SkuInfoVo;
import com.uliky.shouyiLibrary.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    private final String CART_PREFIX = "shouyiLibrary:cart:";

    /**
     * 添加商品到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        //获取购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(s)) {
            //新商品添加到购物车
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程查询商品信息
                SkuInfoVo skuInfo = productFeignService.getSkuInfo(skuId).getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setPrice(skuInfo.getPrice());
            },executor);
            CompletableFuture<Void> getSkuAttrVakuesTask = CompletableFuture.runAsync(() -> {
                //远程调用 -- 查询sku的组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            CompletableFuture.allOf(getSkuInfoTask,getSkuAttrVakuesTask).get();
            String cartItem = JSON.toJSONString(cartItemVo);
            cartOps.put(cartItemVo.getSkuId().toString(),cartItem);
            return cartItemVo;
        }else {
            CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    /**
     * 查询购物车商品
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        CartItemVo cartItem = JSON.parseObject(s, CartItemVo.class);
        return cartItem;
    }

    /**
     * 获取购物车
     * @return
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        //判断用户状态得到对应的购物车
        CartVo cartVo = new CartVo();
        //得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null) {
            //登录
            String carKey = CART_PREFIX +userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(carKey);
            //判断临时购物车有没有数据
            List<CartItemVo> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if(tempCartItems!=null) {
                //需要合并
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            //获取登陆后的购物车信息
            List<CartItemVo> cartItems = getCartItems(carKey);
            cartVo.setItems(cartItems);
        }else {
            //没登录
            String carKey = CART_PREFIX +userInfoTo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(carKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }
    /**
     * 获得的购物车里面的数据
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> products = hashOps.values();
        if(products!=null && products.size()>0) {
            List<CartItemVo> collect = products.stream().map((obj) -> {
                String s = (String) obj;
                CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 拿到购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String carkey = "";
        if(userInfoTo.getUserId() != null) {
            carkey = CART_PREFIX +userInfoTo.getUserId();
        }else {
            carkey = CART_PREFIX +userInfoTo.getUserKey();
        }
        //判断redis存储的数据--hash  有没有该数据
        //绑定购物车
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(carkey);
        return operations;
    }

    /**
     * 清空购物车
     */
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    /**
     * 修改商品选中状态
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true:false);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),jsonString);


    }
    /**
     * 修改商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),jsonString);
    }

    /**
     * 删除方法
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            List<CartItemVo> collect = cartItems.stream()
                    .map(item->{
                        //查询价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        BigDecimal data = price.getData(new TypeReference<BigDecimal>() {});
                        item.setPrice(data);
//                        String key = (String) price.get("data");
//                        item.setPrice(new BigDecimal(key));
                        return item;
                    })
                    .filter(item -> item.getCheck()).collect(Collectors.toList());
            return collect;
        }

    }
}
